<template>
  <div v-if="isLoading" class="loading-container">
    <div class="spinner" />
    <p>数据处理中，请稍候...</p>
  </div>
  <div v-else ref="chartRef" class="chart" />
  <div class="info-box">
    <h3 class="info-title">数据说明</h3>
    <ul class="info-content">
      <li>
        <span class="label">设备待机：</span>
        <span class="value">10000 - 20000</span>
      </li>
      <li>
        <span class="label">调试停机：</span>
        <span class="value">20000 - 25000</span>
      </li>
      <li>
        <span class="label">故障停机：</span>
        <span class="value">30000 - 40000</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, defineExpose } from "vue";
import { useECharts } from "@pureadmin/utils";
import { codeEstimation } from "@/api/dataProcessing";
import * as echarts from "echarts/core";
import { ScatterChart } from "echarts/charts"; // 导入散点图模块

echarts.use([ScatterChart]); // 注册散点图模块

import { LineChart } from "echarts/charts"; // 导入折线图模块
echarts.use([LineChart]); // 注册折线图模块

const chartRef = ref();
const chartData = ref([
  { data: [], name: "估计数据" } // 初始化数据数组
]);
const isLoading = ref(false); // 是否正在加载
const { setOptions } = useECharts(chartRef, {});
const render = () =>
  setOptions({
    title: {
      text: props.currentDevice ? `${props.currentDevice} 估计数据` : "",
      textStyle: {
        fontSize: 15
      }
    },
    xAxis: {
      type: "category",
      name: "样本点/个",
      nameTextStyle: {
        padding: [20, 0, 0, -30],
        verticalAlign: "top"
      }
    },
    yAxis: {
      // 判断设备类型，动态修改 yAxis 的名称
      name: props.currentDevice === "整经机" ? "长度/m" : "电压/mV",
      type: "value",
      nameRotate: 1
    },
    legend: {
      right: "15%",
      data: ["估计数据"],
      icon: "roundRect",
      top: "5%",
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      showDelay: 0,
      formatter: function (params) {
        return `${params.seriesName} :<br/>${params.name} : ${params.value}`;
      },
      axisPointer: {
        show: true,
        type: "cross",
        lineStyle: {
          type: "dashed",
          width: 1
        }
      }
    },
    series: [
      {
        name: "估计数据",
        type: "line",
        data: chartData.value[0].data
      }
    ]
  });

const childStatusObj = ref({
  title: "未估计",
  status: 500
});

const emit = defineEmits(["childTitleStatusClick"]);
emit("childTitleStatusClick", childStatusObj.value);

const props = defineProps({
  selectValue: {
    type: Object,
    default() {
      return {};
    }
  },
  switchValue: {
    type: Array,
    default() {
      return [];
    }
  },
  fileData: {
    type: Object,
    default: null
  },
  fileName: {
    type: String,
    default: ""
  },
  currentDevice: {
    type: String,
    default: ""
  }
});

onMounted(() => {
  render(); // 初始渲染图表
});

const childMethod = () => {
  // 检查是否接收到文件
  if (!props.fileData) {
    childStatusObj.value.title = "未收到文件";
    childStatusObj.value.status = 400;
    emit("childTitleStatusClick", childStatusObj.value);
    return;
  }

  // 重置图表数据
  chartData.value[0].data = [];

  childStatusObj.value.title = "估计中....";
  isLoading.value = true; // 开始加载
  emit("childTitleStatusClick", childStatusObj.value);

  let formData = new FormData();
  formData.append("type", props.selectValue.selectD);
  formData.append("file", props.fileData);

  console.log("上传的文件:", props.fileData);

  codeEstimation(formData)
    .then(res => {
      if (res.status === 200) {
        // 处理数据，如果需要转换格式，可在此进行
        const processedData = res.data.prodata.map((y, x) => [x, y]);
        chartData.value[0].data = processedData;
        // 根据 prodata1 的第一个元素值设置状态标题
        const statusMap = {
          0: "设备待机",
          1: "调试停机",
          2: "故障停机",
          3: "紧急停机",
          4: "正常运行"
        };
        const prodata1FirstValue = Array.isArray(res.data.prodata1)
          ? res.data.prodata1[1]
          : null;

        childStatusObj.value.title =
          statusMap[prodata1FirstValue] || "未知状态";
        render();
        if (res.data.prodata.length > 0) {
          childStatusObj.value.status = res.status;
        }
      } else {
        childStatusObj.value.title = "估计失败";
        childStatusObj.value.status = res.status;
      }
    })
    .catch(error => {
      childStatusObj.value.title = "估计失败";
      childStatusObj.value.status = error.status || 500;
      console.log(error);
    })
    .finally(() => {
      // 数据返回后停止加载
      isLoading.value = false;
      emit("childTitleStatusClick", childStatusObj.value);
    });
};

defineExpose({
  childMethod
});
</script>

<style lang="scss" scoped>
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(0, 0, 0, 0.1);
  border-top-color: #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.chart {
  width: 100%;
  height: 430px;
}
.info-box {
  background-color: #f5f8ff;
  border: 1px solid #d1e3ff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 85%;
  margin: 0 auto;
}

.info-title {
  font-size: 1.2em;
  font-weight: bold;
  color: #004085;
  margin-bottom: 10px;
}

.info-content {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.info-content li {
  margin-bottom: 8px;
  font-size: 0.95em;
  color: #333;
}

.label {
  font-weight: bold;
  color: #0056b3;
}

.value {
  color: #17a2b8;
}
</style>
